﻿using FlashPay.DAO.Bank;
using FlashPay.DAO.Interface;
using FlashPay.EF.Models;
using FlashPay.Entity;
using FlashPay.Entity.Enum;
using FlashPay.Entity.Parameter;
using FlashPay.Entity.Request;
using FlashPay.Entity.Request.Bank;
using FlashPay.Entity.Response.Bank;
using FlashPay.Service.Bank;
using FlashPay.Util;
using FlashPay.Util.StatusCode;
using System;
using System.Collections.Generic;

namespace FlashPay.Service.Impl.Bank
{
    public class BankInfoServiceImpl : BankInfoService
    {
        private readonly BankInfoDAO bankInfoDAO;
        private readonly StatusCodeFactory statusCodeFactory;
        /// <summary>
        /// 日志权限数据接口
        /// </summary>
        private readonly LogDao _logDao;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogRecord _logRecord;

        public BankInfoServiceImpl(BankInfoDAO bankInfoDAO, StatusCodeFactory statusCodeFactory, LogDao logDao, LogRecord logRecord)
        {
            this.bankInfoDAO = bankInfoDAO;
            this.statusCodeFactory = statusCodeFactory;
            this._logDao = logDao;
            this._logRecord = logRecord;
        }

        #region 映射轉換

        private BankInfo MapperRequest<T>(BankInfoRequest<T> model)
        {
            BankInfo request = new BankInfo();
            request.BankCode = model.BankCode;
            request.BankName = model.BankName;
            request.BankFullName = model.BankFullName;
            request.BankEnglishName = model.BankEnglishName;
            request.SortNo = model.SortNo;
            request.BankUrl = model.BankUrl;
            request.BankRemark = model.BankRemark;
            request.BankTel = model.BankTel;
            request.BankAddress = model.BankAddress;

            return request;
        }

        private BankInfoResponse MapperResponse(BankInfo model)
        {
            BankInfoResponse response = new BankInfoResponse();
            response.BankCode = model.BankCode;
            response.BankName = model.BankName;
            response.BankFullName = model.BankFullName;
            response.BankEnglishName = model.BankEnglishName;
            response.BankUrl = model.BankUrl;
            response.BankRemark = model.BankRemark;
            response.BankTel = model.BankTel;
            response.BankAddress = model.BankAddress;

            return response;
        }

        #endregion

        /// <summary>
        /// 銀行新增
        /// </summary>
        public void AddBank(BankInfoRequest<String> model)
        {
            using (bankInfoDAO)
            {
                BankInfo query = new BankInfo();
                query.BankCode = model.BankCode;

                /* 取得資料 */
                Int32? count = GetBankInfoCount(query);

                /* 檢查資料 */
                if (count == null)
                {
                    return;
                }

                if (count != 0)
                {
                    statusCodeFactory.BuildStatus(StatusCode.BANK_INFO_ADD_EXIST_DATA, model);
                    return;
                }

                /* 轉換Model */
                BankInfo request = MapperRequest(model);

                /* 呼叫DAO層 */
                bankInfoDAO.Add(model, request);
            }
        }

        /// <summary>
        /// 銀行修改
        /// </summary>
        public void EditBank(BankInfoRequest<String> model)
        {
            using (bankInfoDAO)
            {
                BankInfo query = new BankInfo();
                query.BankCode = model.BankCode;

                /* 取得資料 */
                Int32? count = GetBankInfoCount(query);

                /* 檢查資料 */
                if (count == null)
                {
                    return;
                }

                if (count == 0)
                {
                    statusCodeFactory.BuildStatus(StatusCode.BANK_INFO_EDIT_CANNOT_FIND_DATA, model);
                    return;
                }

                /* 轉換Model */
                BankInfo request = MapperRequest(model);

                /* 呼叫DAO層 */
                bankInfoDAO.EditUseBankId(model, request);
            }
        }

        /// <summary>
        /// 銀行列表
        /// </summary>
        public void GetBank(BankInfoRequest<List<BankInfoResponse>> model)
        {
            using (bankInfoDAO)
            {
                /* 轉換Model */
                BankInfo request = MapperRequest(model);
                
                BaseModel<List<BankInfo>> model2 = new BaseModel<List<BankInfo>>();
                model2.PageIndex = model.PageIndex;
                model2.PageSize = model.PageSize;

                /* 呼叫DAO層 */
                bankInfoDAO.Get(model2, request);

                /* 檢查資料 */
                if (!model2.Success)
                {
                    return;
                }

                /* 轉換Model */
                List<BankInfoResponse> result = new List<BankInfoResponse>();
                foreach (BankInfo _model in model2.Result)
                {
                    result.Add(MapperResponse(_model));
                }

                /* 結果複製 */
                model.Result = result;
                model.Success = model2.Success;
                model.TotalCount = model2.TotalCount;
            }
        }

        /// <summary>
        /// 銀行數取得
        /// </summary>
        private Int32? GetBankInfoCount(BankInfo request)
        {
            BaseModel<List<BankInfo>> model = new BaseModel<List<BankInfo>>();
            model.PageIndex = model.PageIndex;
            model.PageSize = model.PageSize;

            /* 呼叫DAO層 */
            bankInfoDAO.Get(model, request);

            if (!model.Success)
            {
                return null;
            }

            return model.Result.Count;
        }

        /// <summary>
        /// 分頁查詢所有銀行卡
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<BankInfo> GetList(BankInfoQuery query)
        {
            return bankInfoDAO.GetList(query);
        }

        /// <summary>
        /// 获取所有銀行信息
        /// </summary>
        /// <returns>List</returns>
        public List<BankInfo> GetBankInfoList()
        {
            return bankInfoDAO.GetBankInfoList();
        }

        /// <summary>
        /// 根据编号获取银行信息
        /// </summary>
        /// <param name="SortNo">银行编号</param>
        /// <returns>BankInfo</returns>
        public JResult<BankInfo> GetBankInfoByBankCode(string BankCode)
        {
            JResult<BankInfo> result = new JResult<BankInfo>();
            var resultDAO = bankInfoDAO.GetBankInfoByBankCode(BankCode);
            if (resultDAO != null)
            {
                result.Success = true;
                result.Data = resultDAO;
            }
            return result;
        }
        /// <summary>
        /// 新增银行信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JResult AddBankInfo(BankInfo model, Request request)
        {
            var result = new JResult()
            {
                Success = false
            };
            try
            {
                var resultDao = bankInfoDAO.AddBankInfo(model);
                if (resultDao.Success)
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankInfo_Add.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("新增銀行成功,银行代码：{0}", model.BankCode);
                    _logRecord.RequestData = request.RequestData;
                    _logDao.Insert(_logRecord);
                    result.Success = true;
                }
                else
                {
                    throw new Exception(resultDao.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankInfo_Add.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("新增銀行失败,银行代码：{0}", model.BankCode);
                    _logRecord.RequestData = request.RequestData;
                    _logDao.Insert(_logRecord);

                    result.ErrorMessage = ex.Message;
                }
                catch (Exception e)
                {
                    result.ErrorMessage = e.Message;
                }
            }
            return result;
        }
        /// <summary>
        /// 修改銀行信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JResult UpdateBankInfo(BankInfo model, Request request)
        {
            JResult result = new JResult()
            {
                Success = false
            };
            try
            {
                var resultDao = bankInfoDAO.UpdateBankInfo(model);
                //日志
                _logRecord.LogType = LogRecordLogType.BankInfo_Update.GetHashCode();
                _logRecord.CreateDate = DateTime.Now;
                _logRecord.LogLevel = resultDao ? (sbyte)LogLevel.Success.GetHashCode() : (sbyte)LogLevel.Failure.GetHashCode();
                _logRecord.LogRemark = resultDao ? string.Format("银行信息修改成功,银行编号：{0}", model.BankCode) : string.Format("银行信息修改失败,银行编号：{0}", model.BankCode);
                _logRecord.RequestData = request.RequestData;
                _logDao.Insert(_logRecord);
                if (!resultDao)
                {
                    result.ErrorMessage = "修改失败！";
                }
                else
                {
                    result.Success = true;
                    result.SuccessMessage = "修改成功！";
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankInfo_Update.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.LogRemark = string.Format("银行信息修改失败：{0}", ex.Message);
                    _logRecord.RequestData = request.RequestData;
                    _logDao.Insert(_logRecord);

                    result.ErrorMessage = "服务器发生异常!";
                }
                catch (Exception e)
                {
                    result.ErrorMessage = e.Message;
                }
            }
            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="bankCode">银行代码</param>
        /// <returns></returns>
        public JResult DeleteBankInfo(string bankCode)
        {
            JResult result = new JResult();
            try
            {
                using (bankInfoDAO)
                {
                    bool isUse = false;
                    var resultDAO = bankInfoDAO.Delete(bankCode, out isUse);
                    result.Success = resultDAO;

                    _logRecord.LogType = LogRecordLogType.BankInfo_Delete.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogLevel = resultDAO ? (sbyte)LogLevel.Success.GetHashCode() : (sbyte)LogLevel.Failure.GetHashCode();
                    _logRecord.LogRemark = resultDAO ? string.Format("银行删除成功,银行编号：{0}", bankCode) : (isUse ? string.Format("银行正在使用,银行编号：{0}", bankCode) : string.Format("银行删除失败,银行编号：{0}", bankCode));
                    _logRecord.RequestData = "{\"BankCode\":\"" + bankCode + "\"}";
                    _logDao.Insert(_logRecord);
                    if (isUse)
                    {
                        result.ErrorMessage = "该银行正在使用！";
                    }
                    else
                    {
                        if (!result.Success)
                        {
                            result.ErrorMessage = "删除失败！";
                        }
                        else
                        {
                            result.SuccessMessage = "删除成功！";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankInfo_Delete.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.LogRemark = string.Format("银行删除失败：{0}", ex.Message);
                    _logRecord.RequestData = "{\"BankCode\":\"" + bankCode + "\"}";
                    _logDao.Insert(_logRecord);

                    result.ErrorMessage = "服务器发生异常!";
                }
                catch (Exception e)
                {
                    result.ErrorMessage = "服务器发生异常!";
                }
            }
            return result;
        }
    }
}
